package com.cpit.platform.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.utils.BeanUtil;
import com.cpit.platform.dao.AuthorityRepository;
import com.cpit.platform.dto.Authority;
import com.cpit.platform.service.AuthorityService;

@Service
@Transactional
public class AuthorityServiceImpl implements AuthorityService {
	
	@Autowired
	private AuthorityRepository authRep = null;
	
	public List<Authority> findAll() {
		return authRep.findAll();
	}
	
	public void createAuthority(Authority auth) throws Exception {
		authRep.save(auth);
	}
	
	public void deleteAuthority(Authority auth) throws Exception {
		authRep.delete(auth);
	}
	
	public List<Authority> findByCondition(int page, 
			int size, 
			String order, 
			String orderBy, 
			String pattern) {
		if(orderBy == null || orderBy.length() == 0) {
			orderBy = "id";
		}
		Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Direction.ASC : Direction.DESC;
		PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
		Page<Authority> ret = authRep.findByNameContaining(pattern, request);
		return ret.getContent();
	}
	
	@SuppressWarnings("rawtypes")
	public TableJsonData findByConditionJqg(TableDataQueryCondition cond) {
		if(cond.getSidx() == null || cond.getSidx().length() == 0) {
			cond.setSidx("id");
		}
		Direction der = null;
		if(cond.getSord() == null || cond.getSord().length() == 0) {
			der = Direction.ASC;
		} else 
		    der = cond.getSord().equals(SystemConstant.DIRECTION_ASC) ? Direction.ASC : Direction.DESC;
		PageRequest request = new PageRequest(cond.getPageNumber() - 1, cond.getRowsNumber(), 
				new Sort(der, cond.getSidx()));
		Page<Authority> ret = authRep.findByNameContaining(BeanUtil.getStringIdentifyNull(cond.getQueryCond().get("pattern")), request);
		return new TableJsonData(cond, ret.getTotalElements(), ret.getContent());
	}
	
}
